import 'package:flutter/material.dart';
import 'package:flutter/animation.dart';
import 'package:dio/dio.dart';
import 'package:get/route_manager.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class ForgotPasswordScreen extends StatefulWidget {
  @override
  _ForgotPasswordScreenState createState() => _ForgotPasswordScreenState();
  final dio = Dio(BaseOptions(
    baseUrl: const String.fromEnvironment('BASE_URL', 
        defaultValue: "http://localhost:8080"),
  ));
}

class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> 
    with TickerProviderStateMixin {
  late AnimationController _headerController;
  late Animation<Offset> _headerSlide;
  late Animation<double> _headerFade;
  final _formKey = GlobalKey<FormState>();
  
  // 控制器
  TextEditingController _emailController = TextEditingController();
  TextEditingController _codeController = TextEditingController();
  TextEditingController _newPasswordController = TextEditingController();
  
  // 状态管理
  bool _obscurePassword = true;
  bool _isCountingDown = false;
  int _countdownTime = 60;

  @override
  void initState() {
    super.initState();
    _initHeaderAnimations();
  }

  void _initHeaderAnimations() {
    _headerController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 800),
    )..forward();

    _headerSlide = Tween<Offset>(
      begin: Offset(0, -0.2),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _headerController,
      curve: Curves.easeOutQuad,
    ));

    _headerFade = Tween(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _headerController,
        curve: Interval(0.3, 1.0),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Colors.green[50]!,
              Colors.green[100]!,
            ],
          ),
        ),
        child: SafeArea(
          child: SingleChildScrollView(
            padding: EdgeInsets.all(24),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  _buildHeader(),
                  SizedBox(height: 36),
                  _buildEmailField(),
                  SizedBox(height: 24),
                  _buildVerificationCode(),
                  SizedBox(height: 24),
                  _buildNewPasswordField(),
                  SizedBox(height: 40),
                  _buildSubmitButton(),
                  SizedBox(height: 28),
                  _buildBackToLogin(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 头部动画组件
  Widget _buildHeader() {
    return SlideTransition(
      position: _headerSlide,
      child: FadeTransition(
        opacity: _headerFade,
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text('14:24', style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 14,
                )),
              ],
            ),
            SizedBox(height: 20),
            Text('密码重置', style: TextStyle(
              fontSize: 32,
              fontWeight: FontWeight.bold,
              color: Colors.green[800],
              letterSpacing: 1.2,
            )),
            SizedBox(height: 8),
            Text('请验证您的身份信息', style: TextStyle(
              color: Colors.grey[700],
              fontSize: 16,
            )),
          ],
        ),
      ),
    );
  }

  // 邮箱输入框
  Widget _buildEmailField() {
    return TextFormField(
      controller: _emailController,
      keyboardType: TextInputType.emailAddress,
      decoration: _inputDecoration(Icons.email_outlined, '注册邮箱'),
      validator: (value) => value!.contains('@') ? null : '请输入有效邮箱',
    );
  }

  // 验证码输入框
  Widget _buildVerificationCode() {
    return Row(
      children: [
        Expanded(
          child: TextFormField(
            controller: _codeController,
            keyboardType: TextInputType.number,
            decoration: _inputDecoration(Icons.sms_outlined, '验证码'),
            validator: (value) => value!.length == 6 ? null : '验证码为6位数字',
          ),
        ),
        SizedBox(width: 16),
        Container(
          width: 120,
          child: ElevatedButton(
            onPressed: _isCountingDown ? null : _sendVerificationCode,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.green[700],
              padding: EdgeInsets.symmetric(vertical: 16),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child: _isCountingDown 
                ? Text('${_countdownTime}s', style: TextStyle(color: Colors.white70))
                : Text('获取验证码', style: TextStyle(color: Colors.white)),
          ),
        )
      ],
    );
  }

  // 新密码输入框
  Widget _buildNewPasswordField() {
    return TextFormField(
      controller: _newPasswordController,
      obscureText: _obscurePassword,
      decoration: _inputDecoration(Icons.lock_outlined, '新密码').copyWith(
        suffixIcon: IconButton(
          icon: Icon(_obscurePassword 
              ? Icons.visibility_off 
              : Icons.visibility),
          onPressed: () => setState(() => _obscurePassword = !_obscurePassword),
        ),
      ),
      validator: (value) => value!.length >= 6 ? null : '密码至少6位',
    );
  }

  // 统一输入框样式
  InputDecoration _inputDecoration(IconData icon, String label) {
    return InputDecoration(
      labelText: label,
      prefixIcon: Icon(icon, color: Colors.grey[600]),
      floatingLabelStyle: TextStyle(color: Colors.green[700]),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(12),
        borderSide: BorderSide(color: Colors.green, width: 1.5),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(12),
        borderSide: BorderSide(color: Colors.grey[400]!),
      ),
    );
  }

  // 提交按钮
  Widget _buildSubmitButton() {
    return ElevatedButton(
      onPressed: _submitReset,
      style: ElevatedButton.styleFrom(
        foregroundColor: Colors.white,
        backgroundColor: Colors.green[700],
        padding: EdgeInsets.symmetric(vertical: 18),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        elevation: 4,
        shadowColor: Colors.green.withOpacity(0.3),
      ),
      child: Text('重置密码', style: TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.w600,
        letterSpacing: 1.1,
      )),
    );
  }

  // 返回登录链接
  Widget _buildBackToLogin() {
    return TextButton(
      onPressed: () => Get.back(),
      child: Text.rich(
        TextSpan(
          text: '想起密码了？',
          style: TextStyle(color: Colors.grey[600]),
          children: [
            TextSpan(
              text: '返回登录',
              style: TextStyle(
                color: Colors.green[700],
                fontWeight: FontWeight.bold
              ),
            ),
          ]
        )
      ),
    );
  }

  // 发送验证码逻辑
  void _sendVerificationCode() async {
    if (_emailController.text.isEmpty || 
        !_emailController.text.contains('@')) {
      TDToast.showText('请输入有效邮箱', context: context);
      return;
    }

    setState(() => _isCountingDown = true);
    _startCountdown();

    try {
      final response = await widget.dio.post("/send-reset-code", data: {
        "email": _emailController.text
      });
      
      if (response.data['code'] == 200) {
        TDToast.showText('验证码已发送至邮箱', context: context);
      } else {
        TDToast.showText('发送失败: ${response.data['msg']}', context: context);
      }
    } catch (e) {
      TDToast.showText('网络请求异常', context: context);
    }
  }

  // 倒计时逻辑
  void _startCountdown() {
    Future.delayed(Duration(seconds: 1), () {
      if (_countdownTime > 0) {
        setState(() => _countdownTime--);
        _startCountdown();
      } else {
        setState(() {
          _isCountingDown = false;
          _countdownTime = 60;
        });
      }
    });
  }

  // 提交重置请求
  void _submitReset() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      final response = await widget.dio.post("/reset-password", data: {
        "email": _emailController.text,
        "code": _codeController.text,
        "newPassword": _newPasswordController.text
      });

      if (response.data['code'] == 200) {
        TDToast.showText('密码重置成功', context: context);
        Get.offAllNamed("/login");
      } else {
        TDToast.showText('重置失败: ${response.data['msg']}', context: context);
      }
    } catch (e) {
      TDToast.showText('网络请求异常', context: context);
    }
  }

  @override
  void dispose() {
    _headerController.dispose();
    super.dispose();
  }
}